package com.github.cdisk.xtrans.component.utils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * sql的转换结构
 * 自动处理好占位符,以及每个占位符对应的参数
 * @author Cdisk
 *
 */
public class SqlStruct {

	/** 转换后的sql */
	public String sql;

	/** sql中的参数 */
	public Object[] param;


	public SqlStruct() {}

	public SqlStruct(String sql, Map<String, Object> map) throws SQLException {
		Pattern pattern = Pattern.compile("\\$\\{.*?\\}");
		Matcher matcher = pattern.matcher(StringUtils.trimToEmpty(sql));
		List<Object> param = new ArrayList<Object>();
		while (matcher.find()) {
			if (map == null || map.size() == 0) throw new SQLException("语句需要参数, 但当前没有参数传入.");
			String column = matcher.group().replace("${", "").replace("}", "");
			Object value = map.get(column);
		      if (value == null) {
		        value = map.get(column.toUpperCase());
		      }
		      if (value == null) {
		        value = map.get(column.toLowerCase());
		      }
//			if (!map.containsKey(column) && !map.containsKey(column.toLowerCase())) throw new SQLException("没有找到参数${" + column + "}对应的值.");
			param.add(value);
//			paramString += column + ":" + value + ", ";
		}

		this.sql = sql.replaceAll("\\$\\{.*?\\}", "?");
		this.param = new Object[param.size()];

		for (int i = 0; i < param.size(); i++) {
			this.param[i] = param.get(i);
		}
	}

	@Override
	public String toString() {
		String _sql = this.sql;
		for (Object object : param) {
			if (object instanceof Number) {
				_sql = _sql.replaceFirst("\\?", String.valueOf(object));
			} else {
				_sql = _sql.replaceFirst("\\?", "'".concat(String.valueOf(object).concat("'")));
			}
		}
		return _sql;
	}

}